<template>
  <div class="character-square">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">角色广场</h1>
      <p class="page-description">探索和创建你的专属AI角色</p>
    </div>

    <!-- 加载状态 -->
    <div v-if="charactersLoading" class="loading-container">
      <el-skeleton :rows="3" animated />
      <el-skeleton :rows="3" animated />
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 角色卡片网格 -->
    <div v-else class="character-grid">
      <!-- 动态角色卡片 -->
      <el-card 
        v-for="character in characters" 
        :key="character.id" 
        class="character-card" 
        shadow="hover"
        @click="showCharacterDetail(character.id)"
      >
        <div class="character-avatar">
          <el-avatar 
            :size="80" 
            :src="character.image" 
            :icon="User"
          />
        </div>
        <div class="character-info">
          <h3 class="character-name">{{ character.name }}</h3>
          <p class="character-desc">{{ character.appearance }}</p>
        </div>
      </el-card>

      <!-- 空状态 -->
      <div v-if="characters && characters.length === 0" class="empty-state">
        <el-empty description="暂无角色，快来创建第一个角色吧！" />
      </div>
    </div>

    <!-- 角色详情模态窗口 -->
    <el-dialog
      v-model="showDetailDialog"
      title="角色详情"
      width="700px"
      :before-close="() => showDetailDialog = false"
      class="character-detail-dialog"
    >
      <div v-if="detailLoading" class="detail-loading">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else-if="selectedCharacter" class="character-detail">
        <div class="detail-header">
          <div class="detail-avatar">
            <el-avatar 
              :size="120" 
              :src="selectedCharacter.image" 
              :icon="User"
            />
          </div>
          <div class="detail-info">
            <h2 class="detail-name">{{ selectedCharacter.name }}</h2>
            <p class="detail-appearance">{{ selectedCharacter.appearance }}</p>
          </div>
        </div>
        
        <div class="detail-content">
          <div class="detail-section">
            <h3 class="section-title">背景故事</h3>
            <p class="section-content">{{ selectedCharacter.background }}</p>
          </div>
          
          <div class="detail-section">
            <h3 class="section-title">性格特点</h3>
            <p class="section-content">{{ selectedCharacter.personality }}</p>
          </div>
          
          <div class="detail-section">
            <h3 class="section-title">经典台词</h3>
            <p class="section-content">{{ selectedCharacter.classicLines }}</p>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
          <el-button 
            v-if="followStatus" 
            type="danger" 
            :loading="followLoading"
            @click="handleUnfollow"
          >
            取消关注
          </el-button>
          <el-button 
            v-else 
            type="primary" 
            :loading="followLoading"
            @click="handleFollow"
          >
            关注
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 创建角色对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建角色"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="top"
      >
        <!-- 头像上传 -->
        <el-form-item label="角色头像">
          <div class="avatar-upload">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-change="handleAvatarChange"
              :auto-upload="false"
            >
              <img v-if="avatarPreview" :src="avatarPreview" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">支持 JPG、PNG、WEBP 格式，文件大小不超过 2MB</div>
          </div>
        </el-form-item>

        <!-- 角色名称 -->
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入角色名称"
            :disabled="loading"
          />
        </el-form-item>

        <!-- 外观描述 -->
        <el-form-item label="外观描述" prop="appearance">
          <el-input
            v-model="form.appearance"
            type="textarea"
            :rows="3"
            placeholder="请描述角色的外观特征"
            :disabled="loading"
          />
        </el-form-item>

        <!-- 背景故事 -->
        <el-form-item label="背景故事" prop="background">
          <el-input
            v-model="form.background"
            type="textarea"
            :rows="4"
            placeholder="请描述角色的背景故事"
            :disabled="loading"
          />
        </el-form-item>

        <!-- 性格特点 -->
        <el-form-item label="性格特点" prop="personality">
          <el-input
            v-model="form.personality"
            type="textarea"
            :rows="3"
            placeholder="请描述角色的性格特点"
            :disabled="loading"
          />
        </el-form-item>

        <!-- 经典台词 -->
        <el-form-item label="经典台词" prop="classicLines">
          <el-input
            v-model="form.classicLines"
            type="textarea"
            :rows="3"
            placeholder="请输入角色的经典台词"
            :disabled="loading"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose" :disabled="loading">
            取消
          </el-button>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            创建角色
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, User } from '@element-plus/icons-vue'
import { characterApi } from '../api/character'
import type { CharacterCreateRequest, CharacterInfo, CharacterDetail } from '../api/character'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

// 角色列表相关
const characters = ref<CharacterInfo[]>([])
const charactersLoading = ref(false)
const charactersCache = new Map<string, CharacterDetail>()

// 角色详情相关
const showDetailDialog = ref(false)
const detailLoading = ref(false)
const selectedCharacter = ref<CharacterDetail | null>(null)

// 关注状态相关
const followStatus = ref<boolean>(false)
const followLoading = ref(false)

// 对话框状态
const showCreateDialog = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()

// 头像相关
const avatarFile = ref<File | null>(null)
const avatarPreview = ref('')

// 表单数据
const form = reactive({
  name: '',
  appearance: '',
  background: '',
  personality: '',
  classicLines: ''
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 1, max: 50, message: '角色名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  appearance: [
    { required: true, message: '请输入外观描述', trigger: 'blur' },
    { min: 10, max: 500, message: '外观描述长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  background: [
    { required: true, message: '请输入背景故事', trigger: 'blur' },
    { min: 20, max: 1000, message: '背景故事长度在 20 到 1000 个字符', trigger: 'blur' }
  ],
  personality: [
    { required: true, message: '请输入性格特点', trigger: 'blur' },
    { min: 10, max: 500, message: '性格特点长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  classicLines: [
    { required: true, message: '请输入经典台词', trigger: 'blur' },
    { min: 5, max: 200, message: '经典台词长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 头像上传前验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const isValidType = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'].includes(rawFile.type)
  const isLt2M = rawFile.size / 1024 / 1024 < 2

  if (!isValidType) {
    ElMessage.error('头像图片只能是 JPG、PNG、WEBP 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像选择
const handleAvatarChange: UploadProps['onChange'] = (uploadFile) => {
  if (uploadFile.raw) {
    avatarFile.value = uploadFile.raw
    const reader = new FileReader()
    reader.onload = (e) => {
      avatarPreview.value = e.target?.result as string
    }
    reader.readAsDataURL(uploadFile.raw)
  }
}

// 重置表单
const resetForm = () => {
  form.name = ''
  form.appearance = ''
  form.background = ''
  form.personality = ''
  form.classicLines = ''
  avatarFile.value = null
  avatarPreview.value = ''
  formRef.value?.resetFields()
}

// 关闭对话框
const handleClose = () => {
  if (loading.value) return
  
  const hasContent = form.name || form.appearance || form.background || form.personality || form.classicLines || avatarFile.value
  
  if (hasContent) {
    ElMessageBox.confirm(
      '确定要关闭吗？未保存的内容将会丢失。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      showCreateDialog.value = false
      resetForm()
    }).catch(() => {})
  } else {
    showCreateDialog.value = false
    resetForm()
  }
}

// 获取角色列表
const fetchCharacters = async () => {
  try {
    charactersLoading.value = true
    const response = await characterApi.getSquareList()
    // 后端返回结构：{ code, msg, data: Character[] }，为兼容性考虑，code=0或code=1均视为成功
    const success = response && typeof response === 'object' && (response.code === 0 || response.code === 1)
    if (!success || !Array.isArray(response.data)) {
      throw new Error(response?.msg || '获取角色广场数据失败')
    }
    characters.value = response.data
  } catch (error: any) {
    console.error('获取角色列表失败:', error)
    ElMessage.error(error.message || '获取角色列表失败，请重试')
    characters.value = [] // 确保在错误时也有默认值
  } finally {
    charactersLoading.value = false
  }
}

// 显示角色详情
const showCharacterDetail = async (characterId: number) => {
  try {
    showDetailDialog.value = true
    
    // 检查缓存
    if (charactersCache.has(characterId.toString())) {
      selectedCharacter.value = charactersCache.get(characterId.toString())!
      // 获取关注状态
      await checkFollowStatus(characterId)
      return
    }
    
    detailLoading.value = true
    const response = await characterApi.getDetail(characterId)
    // 根据API返回格式：{code, msg, data: Character}
    selectedCharacter.value = response.data
    
    // 缓存角色详情
    if (response.data) {
      charactersCache.set(characterId.toString(), response.data)
    }
    
    // 获取关注状态
    await checkFollowStatus(characterId)
  } catch (error: any) {
    console.error('获取角色详情失败:', error)
    ElMessage.error('获取角色详情失败，请重试')
    showDetailDialog.value = false
  } finally {
    detailLoading.value = false
  }
}

// 检查关注状态
const checkFollowStatus = async (characterId: number) => {
  try {
    const response = await characterApi.getFollowStatus(characterId)
    if (response.code === 1) {
      followStatus.value = response.data
    }
  } catch (error: any) {
    console.error('获取关注状态失败:', error)
    // 不显示错误消息，静默处理
    followStatus.value = false
  }
}

// 关注角色
const handleFollow = async () => {
  if (!selectedCharacter.value) return
  
  try {
    followLoading.value = true
    const response = await characterApi.followCharacter(selectedCharacter.value.id)
    if (response.code === 1) {
      followStatus.value = true
      ElMessage.success('关注成功！')
    } else {
      throw new Error(response.msg || '关注失败')
    }
  } catch (error: any) {
    console.error('关注失败:', error)
    ElMessage.error(error.message || '关注失败，请重试')
  } finally {
    followLoading.value = false
  }
}

// 取消关注
const handleUnfollow = async () => {
  if (!selectedCharacter.value) return
  
  try {
    followLoading.value = true
    const response = await characterApi.unfollowCharacter(selectedCharacter.value.id)
    if (response.code === 1) {
      followStatus.value = false
      ElMessage.success('已取消关注')
    } else {
      throw new Error(response.msg || '取消关注失败')
    }
  } catch (error: any) {
    console.error('取消关注失败:', error)
    ElMessage.error(error.message || '取消关注失败，请重试')
  } finally {
    followLoading.value = false
  }
}

// 开始对话
const startChat = () => {
  if (selectedCharacter.value) {
    ElMessage.info('对话功能即将上线，敬请期待！')
    // TODO: 实现跳转到对话页面的逻辑
    // router.push(`/chat/${selectedCharacter.value.id}`)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true

    const characterData: CharacterCreateRequest = {
      name: form.name.trim(),
      appearance: form.appearance.trim(),
      background: form.background.trim(),
      personality: form.personality.trim(),
      classicLines: form.classicLines.trim()
    }

    let characterId: number
    
    // 先创建角色，依据后端返回的 { code, data } 结构拿到角色ID
    const createResp = await characterApi.create(characterData)
    if (createResp.code !== 1 || !createResp.data) {
      throw new Error(createResp.msg || '创建角色失败')
    }
    characterId = createResp.data

    // 如选择了头像，则在拿到角色ID后再上传头像
    if (avatarFile.value) {
      await characterApi.uploadAvatar(avatarFile.value, characterId)
    }

    ElMessage.success('角色创建成功！')
    showCreateDialog.value = false
    resetForm()
    
    // 刷新角色列表
    await fetchCharacters()
    
  } catch (error: any) {
    console.error('创建角色失败:', error)
    ElMessage.error(error.message || '创建角色失败，请重试')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取角色列表
onMounted(() => {
  fetchCharacters()
})
</script>

<style scoped>
.character-square {
  padding: 0;
  min-height: calc(100vh - 40px);
}

.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-title {
  font-size: 32px;
  font-weight: bold;
  color: #ec4899;
  margin: 0 0 10px 0;
}

.page-description {
  font-size: 16px;
  color: #be185d;
  margin: 0;
}

.character-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 80px;
}

.character-card {
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid #f9a8d4;
  position: relative;
  overflow: hidden;
}

.character-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(236, 72, 153, 0.1), transparent);
  transition: left 0.5s;
}

.character-card:hover {
  transform: translateY(-8px) scale(1.02);
  box-shadow: 0 12px 35px rgba(236, 72, 153, 0.2);
  border-color: #ec4899;
}

.character-card:hover::before {
  left: 100%;
}

.character-card:active {
  transform: translateY(-4px) scale(1.01);
  transition: all 0.1s ease;
}

.character-avatar {
  text-align: center;
  margin-bottom: 15px;
}

.character-info {
  text-align: center;
}

.character-name {
  font-size: 18px;
  font-weight: 600;
  color: #ec4899;
  margin: 0 0 8px 0;
}

.character-desc {
  font-size: 14px;
  color: #be185d;
  margin: 0;
  line-height: 1.4;
}

.create-fab {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  box-shadow: 0 4px 12px rgba(236, 72, 153, 0.3);
  z-index: 1000;
}

.avatar-upload {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  display: block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c8c8c;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border: 2px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease;
}

.avatar-uploader-icon:hover {
  border-color: #ec4899;
  color: #ec4899;
}

.upload-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #999;
}

.loading-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 80px;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
}

/* 角色详情模态窗口样式 */
.character-detail-dialog .el-dialog__body {
  padding: 20px;
}

.character-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-avatar {
  margin-right: 20px;
  flex-shrink: 0;
}

.detail-info {
  flex: 1;
}

.detail-name {
  font-size: 24px;
  font-weight: bold;
  color: #ec4899;
  margin: 0 0 10px 0;
}

.detail-appearance {
  font-size: 16px;
  color: #be185d;
  margin: 0;
  line-height: 1.5;
}

.detail-content {
  space-y: 20px;
}

.detail-section {
  margin-bottom: 25px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #ec4899;
  margin: 0 0 10px 0;
  padding-bottom: 5px;
  border-bottom: 2px solid #f9a8d4;
}

.section-content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin: 0;
  padding: 10px 0;
}

.detail-loading {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .character-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 15px;
  }
  
  .create-fab {
    bottom: 20px;
    right: 20px;
    width: 50px;
    height: 50px;
  }
  
  .page-title {
    font-size: 24px;
  }
}
</style>